package com.grademaster.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grademaster.common.R;
import com.grademaster.dto.CoursePageDto;
import com.grademaster.dto.CourseTeacherPageDto;
import com.grademaster.entity.*;
import com.grademaster.mapper.CoursesMapper;
import com.grademaster.service.*;
import com.grademaster.util.LoginUtil;
import com.grademaster.vo.CourseTeacherVO;
import com.grademaster.vo.CourseVO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
* @author Administrator
* @description 针对表【courses(课程表)】的数据库操作Service实现
* @createDate 2024-06-25 13:57:00
*/
@Service
public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses>
    implements CoursesService {

    @Autowired
    private CoursesMapper coursesMapper;
    @Autowired
    private TermsService termsService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private ScoresService scoresService;
    @Autowired
    private ClassesService classesService;


    /**
     * 获取分页课程数据
     *
     * @param coursePageDto
     * @return
     */
    @Override
    public R getCoursesPage(CoursePageDto coursePageDto) {
        //判断是否登录
        StpUtil.isLogin();

        String userId = null;
        //判断是不是超级管理员，不是超级管理员只能查询自己的Id下的成绩
        if(!LoginUtil.isAdmin()){
            userId = LoginUtil.getLoginUserId();
        }
        //获取分页列表
        List<CourseVO> voList = coursesMapper.getCourseInfoByPage(coursePageDto.getTermName(), userId, coursePageDto.getPage(), coursePageDto.getPageSize());
        //获取总记录数
        int count = coursesMapper.countCourseInfo(coursePageDto.getTermName(), userId);

        //封装分页结果
        Page<CourseVO> courseVOPage = new Page<>(coursePageDto.getPage(), coursePageDto.getPageSize(), count);
        courseVOPage.setRecords(voList);

        return R.success(courseVOPage);
    }
    /**
     * 导出课程数据
     *
     * @param coursePageDto
     * @return
     */
    @Override
    public ResponseEntity exportExcel(CoursePageDto coursePageDto) {
        //判断是否登录
        StpUtil.isLogin();

        String userId = null;
        //判断是不是超级管理员，不是超级管理员只能查询自己的Id下的成绩
        if(!LoginUtil.isAdmin()){
            userId = LoginUtil.getLoginUserId();
        }
        //获取分页列表
        List<CourseVO> voList = coursesMapper.getCourseInfoByPage(coursePageDto.getTermName(), userId, 1, 2000);
        Workbook workbook = new XSSFWorkbook();

        // Create a sheet named "Courses"
        Sheet sheet = workbook.createSheet("Courses");

        // Create header row
        Row headerRow = sheet.createRow(0);
        String[] headers = {"学期名称", "课程名称", "课程类型"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // Create data rows
        int rowNum = 1;
        for (CourseVO course : voList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(course.getTermName());
            row.createCell(1).setCellValue(course.getCourseName());
            row.createCell(2).setCellValue(course.getClassName());
        }

        // Auto-size columns (optional)
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // Write workbook to ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Create InputStreamResource to wrap ByteArrayInputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        InputStreamResource resource = new InputStreamResource(inputStream);

        // Set response headers
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=courses.xlsx");

        // Return ResponseEntity with Excel file as body
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }




    /**
     * 获取教师课程数据
     *
     * @return
     */
    @Override
    public R getCoursesListByTeacher() {
        //判断是否登录
        StpUtil.isLogin();

        //获取教师id
        //判断是不是超级管理员，不是超级管理员只能查询自己的Id相关的学期数据
        String userId = null;
        if(!LoginUtil.isAdmin()){
            userId = LoginUtil.getLoginUserId();
        }
        //获取数据
        List<String> courseList = coursesMapper.selectDistinctCourseNamesByTeacherId(userId);
        return R.success(courseList);
    }

    /**
     * 获取学生课程数据
     *
     * @return
     */
    @Override
    public R getCoursesListByStudent() {
        //判断是否登录
        StpUtil.isLogin();

        //获取教师id
        //判断是不是超级管理员，不是超级管理员只能查询自己的Id相关的学期数据
        String userId = null;
        if(!LoginUtil.isAdmin()){
            userId = LoginUtil.getLoginUserId();
        }
        //获取数据
        List<String> courseList = coursesMapper.selectDistinctCourseNamesByStudentId(userId);
        return R.success(courseList);
    }

    /**
     * 获取教师课程分页数据
     *
     * @param courseTeacherPageDto
     * @return
     */
    @Override
    public R getpageCourseTeacher(CourseTeacherPageDto courseTeacherPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        List<CourseTeacherVO> voList = coursesMapper.selectCoursesByConditions(
                courseTeacherPageDto.getName(),
                courseTeacherPageDto.getTermName(),
                courseTeacherPageDto.getClassName(),
                courseTeacherPageDto.getCourseName(),
                courseTeacherPageDto.getPage(),
                courseTeacherPageDto.getPageSize()
        );
        int count = coursesMapper.countCoursesByConditions(
                courseTeacherPageDto.getName(),
                courseTeacherPageDto.getTermName(),
                courseTeacherPageDto.getClassName(),
                courseTeacherPageDto.getCourseName()
        );

        Page<CourseTeacherVO> courseTeacherVOPage = new Page<>(courseTeacherPageDto.getPage(), courseTeacherPageDto.getPageSize(), count);
        courseTeacherVOPage.setRecords(voList);
        return R.success(courseTeacherVOPage);
    }



    /**
     * 生成成绩
     *
     * @param courseTeacherPageDto
     * @return
     */
    @Override
    public R generateScore(CourseTeacherPageDto courseTeacherPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        List<CourseTeacherVO> voList = coursesMapper.selectCoursesByConditions(
                courseTeacherPageDto.getName(),
                courseTeacherPageDto.getTermName(),
                courseTeacherPageDto.getClassName(),
                courseTeacherPageDto.getCourseName(),
                1,
                2000
        );
        for (CourseTeacherVO vo : voList) {
            //获取课程Id
            Long courseId = vo.getCourseId();
            //获取学期Id
            Long termId = termsService.getOne(new LambdaQueryWrapper<Terms>().eq(Terms::getTermName, vo.getTermName())).getTermId();
            //获取班级Id
            Long classId = classesService.getOne(new LambdaQueryWrapper<Classes>().eq(Classes::getClassName, vo.getClassName())).getClassId();
            //获取学生列表
            List<StudentInfo> studentInfoList = studentInfoService.list(new LambdaQueryWrapper<StudentInfo>().eq(StudentInfo::getClassId, classId));
            for (StudentInfo studentInfo : studentInfoList) {
                //获取学生Id
                Long studentId = studentInfo.getStudentId();
                //放进成绩表
                Scores scores = new Scores();
                scores.setStudentId(studentId);
                scores.setTermId(termId);
                scores.setCourseId(courseId);
                scores.setScoreValue(BigDecimal.valueOf(0));
                scores.setVerificationStatus(0);
                scoresService.save(scores);
            }
        }
        return R.success("成绩生成成功");
    }

    /**
     * 导出成绩2
     *
     * @param courseTeacherPageDto
     * @return
     */
    @Override
    public ResponseEntity exportExcel2(CourseTeacherPageDto courseTeacherPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return ResponseEntity.badRequest().build();
        }
        List<CourseTeacherVO> voList = coursesMapper.selectCoursesByConditions(
                courseTeacherPageDto.getName(),
                courseTeacherPageDto.getTermName(),
                courseTeacherPageDto.getClassName(),
                courseTeacherPageDto.getCourseName(),
                courseTeacherPageDto.getPage(),
                courseTeacherPageDto.getPageSize()
        );
        Workbook workbook = new XSSFWorkbook();

        // 创建一个工作表
        Sheet sheet = workbook.createSheet("Course Teachers");

        // 创建表头
        String[] headers = {"课程ID", "教师名称", "学期名称", "班级名称", "课程名称"};
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 写入数据
        int rowNum = 1;
        for (CourseTeacherVO courseTeacherVO : voList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(courseTeacherVO.getCourseId());
            row.createCell(1).setCellValue(courseTeacherVO.getTeacherName());
            row.createCell(2).setCellValue(courseTeacherVO.getTermName());
            row.createCell(3).setCellValue(courseTeacherVO.getClassName());
            row.createCell(4).setCellValue(courseTeacherVO.getCourseName());
        }

        // 自动调整列宽（可选）
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 将工作簿写入 ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace(); // 实际应用中应该处理异常
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 创建 ByteArrayInputStream 和 InputStreamResource
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 设置响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=courses.xlsx");

        // 返回 ResponseEntity 包含 Excel 文件作为响应体
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    /**
     * 添加或编辑课程
     *
     * @param courses
     * @return
     */
    @Override
    public R addOrEditCourse(Courses courses) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        if (courses.getCourseId()!=null){
            //修改学院
            return R.success(this.updateById(courses));
        }
        //添加学院
        return R.success(this.save(courses));
    }

    /**
     * 删除课程
     *
     * @param courseId
     * @return
     */
    @Override
    public R deleteCourse(String courseId) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        String[] ids = courseId.split(",");
        for (String id : ids) {
            this.removeById(id);
        }
        return R.success("删除成功");
    }



}




